<template>

  <el-card>
    <el-input placeholder="请输入会议名称" v-model="SearchData.AppointmentsName" style="width: 200px;" />
    <el-button type="primary" @click="GetTableData">搜索</el-button>
    
  </el-card>

  &nbsp;

  <el-card>

    <el-button type="primary" @click="openAddDialog" style="margin-left: 10px;">预约会议</el-button>
    &nbsp;
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" />
      <el-table-column label="会议时间">
        <template #default="{ row }">
          {{ formatDate(row.CreateTime) }} {{ formatOnlyTime(row.StartTime) }}-{{ formatOnlyTime(row.EndTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="AppointmentsName" label="会议名称" />
      <el-table-column prop="MeetStatus" label="会议状态">
        <template #default="{ row }">
          <el-tag :type="getMeetStatusType(row.MeetStatus)">
            {{ getMeetStatusText(row.MeetStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="MeetAdmin" label="会议室管理员" />
      <el-table-column prop="MeetAddr" label="会议室" />
      <el-table-column prop="MeetPeople" label="使用人" />
      <el-table-column prop="MeetMain" label="会议主题" />
      <el-table-column fixed="right" label="操作列" min-width="120">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleViewDetails(row)">
            详情
          </el-button>
          <el-button link type="primary" size="small" :disabled="row.MeetStatus === 2" @click="handleEdit(row)">修改会议</el-button>
          <el-button link type="primary" size="small" :disabled="row.MeetStatus === 0" @click="handleViewSummary(row)">会议纪要</el-button>
          <el-button v-if="row.MeetStatus === 12" link type="warning" size="small" @click="handleResubmit(row.AppointmentsId)">重新提交</el-button>
        </template>
      </el-table-column>
    </el-table>

    <table>
      <td>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="SearchData.PageIndex"
              v-model:page-size="SearchData.PageSize"
              :page-sizes="[5, 10, 15, 30]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="SearchData.TotalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </td>
        </tr>
      </td>
    </table>

  </el-card>

  <el-dialog :title="isEdit ? '修改会议' : '会议预约'" v-model="dialogVisible" width="900px" class="appoint-dialog">
    <div class="section-title">
      <span class="bar"></span> 基本信息
    </div>
    <el-form :model="form" label-width="110px" class="appoint-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="会议名称" required>
            <el-input v-model="form.AppointmentsName" placeholder="请输入会议名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议主题" required>
            <el-input v-model="form.MeetMain" placeholder="请输入会议主题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议地点" required>
            <el-select v-model="form.MeetManagerId" placeholder="请选择会议室">
              <el-option :value="0" label="请选择"></el-option>
              <el-option :value="1" label="办公楼606"></el-option>
              <el-option :value="2" label="办公楼501"></el-option>
              <el-option :value="3" label="办公楼502"></el-option>
              <el-option :value="4" label="办公楼503"></el-option>
              <el-option :value="5" label="行政楼-100"></el-option>
              <el-option :value="6" label="行政楼-101"></el-option>
              <el-option :value="7" label="行政楼-201"></el-option>
              <el-option :value="8" label="行政楼-501"></el-option>
              <el-option :value="9" label="行政楼-502"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主持人" required>
            <el-input v-model="form.MeetPeople" placeholder="主持人" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议时间" required>
            <el-date-picker v-model="form.CreateTime" type="date" placeholder="请选择日期" style="width: 160px; margin-right: 10px;" />
            <el-time-picker v-model="form.StartTime" placeholder="开始时间" style="width: 120px; margin-right: 10px;" />
            <span>—</span>
            <el-time-picker v-model="form.EndTime" placeholder="结束时间" style="width: 120px; margin-left: 10px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议参与人" required>
            <el-input v-model="form.JoinPeople" placeholder="参与人" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议内容" required>
            <el-input v-model="form.MeetDesc" type="textarea" placeholder="会议内容" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="section-title" style="margin-top: 20px;">
        <span class="bar"></span> 会议设置
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="会议签到" required>
            <el-radio-group v-model="form.MeetSign">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议口令" required>
            <el-radio-group v-model="form.MeetPassphrase">
              <el-radio-button :label="true">开启</el-radio-button>
              <el-radio-button :label="false">关闭</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="短信通知" required>
            <el-radio-group v-model="form.MeetMessage">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否远程会议" required>
            <el-radio-group v-model="form.MeetRemote">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="width:100%;display:flex;justify-content:flex-end;gap:10px;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="isEdit ? handleUpdate() : handleSubmit()">确定</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { ref,reactive,onMounted } from 'vue';
import { GetAppointmentList } from '@/api/Readapi'
import { useRouter } from 'vue-router';
import { AddAppointment, UpdateAppointment, GetAppointmentsIdToProcess } from '@/api/Writeapi'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter();
const tableData = ref([])

const SearchData = reactive({
  PageIndex: 1,
  PageSize: 5,
  AppointmentsName: '',
  TotalCount: 0,
  TotalPage: 0,
})

const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({
  AppointmentsName: '',
  AppointmentsTemplate: 0,
  MeetMain: '',
  MeetManagerId: 0,
  MeetPeople: '',
  CreateTime: new Date(),
  StartTime: new Date(),
  EndTime: new Date(),
  JoinPeople: '',
  MeetDesc: '',
  MeetSign: false,
  MeetPassphrase: false,
  MeetMessage: false,
  MeetRemote: false,
  MeetStatus: 0,
  AppointmentsId: 0
})

const GetTableData =async () => {
  const res = await GetAppointmentList({
    PageIndex: SearchData.PageIndex,
    PageSize: SearchData.PageSize,
    AppointmentsName: SearchData.AppointmentsName,
  })
  tableData.value = res.data.data
  SearchData.TotalCount = res.data.TotalCount
  SearchData.TotalPage = res.data.totalPage
}

onMounted(() => {
  GetTableData()
})

const handleSizeChange = (val: number) => {
  SearchData.PageSize = val
  GetTableData()
}
const handleCurrentChange = (val: number) => {
  SearchData.PageIndex = val
  GetTableData()
}

// 获取会议状态文本
const getMeetStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未开始'
    case 1:
      return '进行中'
    case 2:
      return '已结束'
    case 10:
        return '待审批'
    case 11:
      return '已审批'
    case 12:
      return '已驳回'
    default:
      return '未知状态'
  }
}

// 获取会议状态标签类型
const getMeetStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 10:
      return 'warning'
    case 11:
      return 'success'
    case 12:
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期部分（年月日）
const formatDate = (dateTime: string | Date) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
}

// 格式化时间部分（时分）
const formatOnlyTime = (dateTime: string | Date) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 查看会议详情
const handleViewDetails = (row: any) => {
  // 使用sessionStorage存储会议数据
  sessionStorage.setItem('appointmentData', JSON.stringify(row));
  router.push({
    path: '/appointment-details',
    query: { id: row.AppointmentsId }
  });
}

// 查看会议纪要
const handleViewSummary = (row: any) => {
  // 使用sessionStorage存储会议数据
  sessionStorage.setItem('appointmentData', JSON.stringify(row));
  router.push({
    path: '/appointment-summary',
    query: { id: row.AppointmentsId }
  });
}

const handleSubmit = async () => {
    // 设置会议模板默认值
    form.AppointmentsTemplate = 0
    const res: any = await AddAppointment(form)
    console.log(res)
    if (res.code == 200) {
      ElMessage.success('预约成功')
      dialogVisible.value = false
      GetTableData()
    }else{
      ElMessage.error(res.msg)
    }

}

// 处理编辑会议
const handleEdit = (row: any) => {
  isEdit.value = true
  dialogVisible.value = true
  
  // 复制当前行数据到表单
  form.AppointmentsName = row.AppointmentsName 
  form.AppointmentsTemplate = row.AppointmentsTemplate 
  form.MeetMain = row.MeetMain 
  form.MeetManagerId = row.MeetManagerId 
  form.MeetPeople = row.MeetPeople
  form.CreateTime = row.CreateTime ? new Date(row.CreateTime) : new Date()
  form.StartTime = row.StartTime ? new Date(row.StartTime) : new Date()
  form.EndTime = row.EndTime ? new Date(row.EndTime) : new Date()
  form.JoinPeople = row.JoinPeople 
  form.MeetDesc = row.MeetDesc 
  form.MeetSign = row.MeetSign
  form.MeetPassphrase = row.MeetPassphrase
  form.MeetMessage = row.MeetMessage
  form.MeetRemote = row.MeetRemote
  form.MeetStatus = row.MeetStatus
  
  // 保存当前编辑的会议ID
  form.AppointmentsId = row.AppointmentsId
}

// 处理更新会议
const handleUpdate = async () => {
    const res: any = await UpdateAppointment(form)
    console.log(res)
    if (res.code == 200) { 
      ElMessage.success('修改成功')
      dialogVisible.value = false
      isEdit.value = false
      GetTableData()
    } else {
      ElMessage.error(res.msg)
    }
}

const resetForm = () => {
  form.AppointmentsName = '';
  form.AppointmentsTemplate = 0;
  form.MeetMain = '';
  form.MeetManagerId = 0;
  form.MeetPeople = '';
  form.CreateTime = new Date();
  form.StartTime = new Date();
  form.EndTime = new Date();
  form.JoinPeople = '';
  form.MeetDesc = '';
  form.MeetSign = false;
  form.MeetPassphrase = false;
  form.MeetMessage = false;
  form.MeetRemote = false;
  form.MeetStatus = 0;
  form.AppointmentsId = 0;
}

const openAddDialog = () => {
  resetForm();
  isEdit.value = false;
  dialogVisible.value = true;
}

// 重新提交会议
const handleResubmit = (id: number) => {
  ElMessageBox.confirm(
    '确定要重新提交吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res:any = await GetAppointmentsIdToProcess({ id: id })
    if (res.code == 200) {
      ElMessage.success('重新提交成功')
      GetTableData()
    } else {
      ElMessage.error(res.msg || '重新提交失败')
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    })
  })
}

</script>

<style scoped>
.appoint-dialog .section-title {
  font-weight: bold;
  font-size: 16px;
  margin: 10px 0 16px 0;
  display: flex;
  align-items: center;
}
.appoint-dialog .section-title .bar {
  display: inline-block;
  width: 5px;
  height: 20px;
  background: #409EFF;
  border-radius: 2px;
  margin-right: 8px;
}
.appoint-form .el-form-item {
  margin-bottom: 18px;
}
</style>
